|
1
|
|
|
import { CommandHandler } from '@nestjs/cqrs'; |
|
2
|
|
|
import { Inject } from '@nestjs/common'; |
|
3
|
|
|
import { IPasswordEncoder } from 'src/Application/IPasswordEncoder'; |
|
4
|
|
|
import { UpdateProfileCommand } from './UpdateProfileCommand'; |
|
5
|
|
|
import { IUserRepository } from 'src/Domain/User/Repository/IUserRepository'; |
|
6
|
|
|
import { IsEmailAlreadyExist } from 'src/Domain/User/Specification/IsEmailAlreadyExist'; |
|
7
|
|
|
import { EmailAlreadyExistException } from 'src/Domain/User/Exception/EmailAlreadyExistException'; |
|
8
|
|
|
import { UserNotFoundException } from 'src/Domain/User/Exception/UserNotFoundException'; |
|
9
|
|
|
|
|
10
|
|
|
@CommandHandler(UpdateProfileCommand) |
|
11
|
|
|
export class UpdateProfileCommandHandler { |
|
12
|
|
|
constructor( |
|
13
|
|
|
@Inject('IUserRepository') |
|
14
|
|
|
private readonly userRepository: IUserRepository, |
|
15
|
|
|
@Inject('IPasswordEncoder') |
|
16
|
|
|
private readonly passwordEncoder: IPasswordEncoder, |
|
17
|
|
|
private readonly isEmailAlreadyExist: IsEmailAlreadyExist |
|
18
|
|
|
) {} |
|
19
|
|
|
|
|
20
|
|
|
public async execute(command: UpdateProfileCommand): Promise<void> { |
|
21
|
|
|
const { firstName, lastName, password, id } = command; |
|
22
|
|
|
const email = command.email.toLowerCase(); |
|
23
|
|
|
|
|
24
|
|
|
const user = await this.userRepository.findOneById(id); |
|
25
|
|
|
if (!user) { |
|
26
|
|
|
throw new UserNotFoundException(); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if ( |
|
30
|
|
|
email !== user.getEmail() && |
|
31
|
|
|
true === (await this.isEmailAlreadyExist.isSatisfiedBy(email)) |
|
32
|
|
|
) { |
|
33
|
|
|
throw new EmailAlreadyExistException(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
user.update(firstName, lastName, email); |
|
37
|
|
|
|
|
38
|
|
|
if (password) { |
|
39
|
|
|
user.updatePassword(await this.passwordEncoder.hash(password)); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
await this.userRepository.save(user); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|